//
//  YKTabBarButton.m
//  youkan
//
//  Created by mac mini on 16/2/25.
//  Copyright © 2016年 Honsintech. All rights reserved.
//

#import "YKTabBarButton.h"
#import "YKBadgeView.h"

#define  YKImageRidio 0.7

@interface YKTabBarButton ()

@property (nonatomic , weak)YKBadgeView *badgeView;

@end

@implementation YKTabBarButton

// 重写setHighlighted，取消高亮做的事情
-(void)setHighlighted:(BOOL)highlighted{}

//懒加载badgeView
-(YKBadgeView *)badgeView{
    if (_badgeView ==nil) {
        YKBadgeView *btn =[YKBadgeView buttonWithType:UIButtonTypeCustom];
        [self addSubview:btn];
        _badgeView =btn;
    }
    return _badgeView;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self =[super initWithFrame:frame]) {
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
        self.imageView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:12];
    }
    return self;
}
//传递UITabBarItem 给tabBarButton，给tabBarButton内容赋值
-(void)setItem:(UITabBarItem *)item{
    _item = item;
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
    // KVO：时刻监听一个对象的属性有没有改变 。 <监听item的改变>
    // 给谁添加观察者
    // Observer:按钮
    [item addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [item addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:nil];
    [item addObserver:self forKeyPath:@"selectedImage" options:NSKeyValueObservingOptionNew context:nil];
    [item addObserver:self forKeyPath:@"badgeValue" options:NSKeyValueObservingOptionNew context:nil];

}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    [self setTitle:_item.title forState:UIControlStateNormal];
    [self setImage:_item.image forState:UIControlStateNormal];
    [self setImage:_item.selectedImage forState:UIControlStateSelected];
    self.badgeView.badgeValue = _item.badgeValue;

}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGFloat W=self.bounds.size.width;
    CGFloat H = self.bounds.size.height ;

    CGFloat imageX = 0;
    CGFloat imageY = 0;
    CGFloat imageW = W;
    CGFloat imageH =H *YKImageRidio;
    self.imageView.frame =CGRectMake(imageX, imageY, imageW, imageH);

    CGFloat titleX = 0;
    CGFloat titleY =imageH-3;
    CGFloat titleW = W;
    CGFloat titleH = H-titleY;
    self.titleLabel.frame =CGRectMake(titleX, titleY, titleW, titleH);

    self.badgeView.x = self.width-self.badgeView.width-10;
    self.badgeView.y=0;

}


@end
